package com.atguigu.gulimall.inteceptor;

import com.atguigu.gulimall.common.constant.CartConstant;
import com.atguigu.gulimall.common.vo.MemberVo;
import com.atguigu.gulimall.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 */
public class CartInteceptor implements HandlerInterceptor {
    // threadLocal 在同一个线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo memberVo = (MemberVo) session.getAttribute("loginUser");
        if (memberVo != null) {
            // 用户登录
            userInfo.setUserId(memberVo.getId()+"");

        } else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    if (name.equals(CartConstant.USER_KEY)) {
                        userInfo.setUserId(name);
                        userInfo.setTempUser(true);
                        break;
                    }
                }
            }
        }
        if (userInfo.getUserKey() == null) {
            userInfo.setUserKey(UUID.randomUUID().toString());
        }
        threadLocal.set(userInfo);
        return true;
    }

    // 目标方法之后，页面渲染之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 命令浏览器保存一个key
        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo.isTempUser() == false) {
            // 表示没有这个临时用户，我们创建
            Cookie cookie = new Cookie(CartConstant.USER_KEY, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.USER_KEY_TIMEOUT);
            response.addCookie(cookie);
            threadLocal.set(userInfoTo);
        }
    }
}
